<template>
  <div>
    <!-- 选择参保方案 -->
    <a-modal :title="'参保'" :visible="isCloseMethods" width="690px" :destroy-on-close="true" @cancel="handleCancels">
      <template slot="footer">
        <!-- <a-button
            type="danger"
            ghost
            v-if="editPlan && (tempEmpSocStatus === 2 || tempEmpSocStatus === 3)"
            @click="cancelZengY"
          >
            {{ getStatusTitle() }}
          </a-button> -->
        <a-button @click="handleCancel"> 取消 </a-button>
        <a-button key="submit" type="primary" @click="finishEdit">
          <!-- {{ editPlan ? "确定" : "下一步" }} -->
          确定
        </a-button>
      </template>

      <div style="padding: 0 56px">
        <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 15 }">
          <a-form-item class="baseInfo-item" label="参保时间">
            <a-month-picker
              :default-value="moment(year + '-' + month, monthFormat)"
              style="margin-left: 20px"
              @change="onYearMonthChange"
            />
            <!-- :disabled-date="disabledDates" -->
            <div
              style="
                  color: #a6a8b4;
                  font-size: 10px;
                  margin-top: -10px;
                  margin-left: 20px;
                "
            >
              若需对之前月份进行补收，请前往社保名单进行设置
            </div>
          </a-form-item>
          <a-form-item class="baseInfo-item" label="业务类型">
            <a-radio-group v-model="typeValue" @change="onTypeChange" style="margin-left: 20px">
              <a-radio :value="1"> 增加/开户 </a-radio>
              <a-radio :value="2"> 续保/调入 </a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item class="baseInfo-item" label="参保方案">
            <a-select
              :default-value="defaultFangan === 0 ? '请选择参保方案' : defaultFangan"
              @change="chooseProgNames"
              placeholder="请选择参保方案"
            >
              <a-select-option v-for="item in progNameLists" :key="item.id">{{ item.progName }}</a-select-option>
            </a-select>
          </a-form-item>

          <div style="margin-bottom:15px;margin-left:50px;margin-top:20px;color:#000000;font-weight:700;">
            社保各项目基数
          </div>
          <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 15 }" class="baseInfo">
            <template v-for="(item, index) in formData">
              <a-form-item v-if="item.itemType === 1" :key="index" :label="item.itemName + '基数'" class="baseInfo-item">
                <a-input-number
                  :value="onlySocAmount ? item.cardinalityDefaultAmount : item.cardinalityDefault"
                  :max="item.cardinalityMax"
                  :min="item.cardinalityMin"
                  @change="val => changeDefault(val, index)"
                />
                <span style="margin-left: 0"> 基数范围[{{ item.cardinalityMin }}-{{ item.cardinalityMax }}]</span>
              </a-form-item>
            </template>
          </a-form>
          <div v-if="!payProvidentFund">
            <div style="margin-bottom:15px;margin-left:50px;color:#000000;font-weight:700;">
              公积金各项基数
            </div>
            <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 15 }" class="baseInfo">
              <template v-for="(item, index) in formData">
                <a-form-item v-if="item.itemType === 2" :key="index" :label="item.itemName + '基数'" class="baseInfo-item">
                  <a-input-number
                    :value="onlySocAmount ? item.cardinalityDefaultAmount : item.cardinalityDefault"
                    :max="item.cardinalityMax"
                    :min="item.cardinalityMin"
                    @change="val => changeDefault(val, index)"
                  />
                  <span style="margin-left: 0"> 基数范围[{{ item.cardinalityMin }}-{{ item.cardinalityMax }}]</span>
                </a-form-item>
              </template>
            </a-form>
          </div>
        </a-form>
      </div>
    </a-modal>
    <a-modal :title="'参保'" :visible="Dvisible" @cancel="handleCancels" :destroy-on-close="true">
      <template slot="footer">
        <a-button key="back" @click="DhandleCancel"> 上一步 </a-button>
        <a-button key="submit" type="primary" @click="DhandleOk">
          确定
        </a-button>
      </template>
      <div class="rowdalog2">
        <img style="width:30px; height:30px;margin-right:10px;" src="@/assets/icons/ask.png" />

        <div style="margin-top:4px;color:#3C3D43;font-size:16px;font-weight: 400;">
          参保后社保将有较大金额变动，确定添加{{ staffList.length }}人？
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
import moment from "moment";
import { getListAllRelation, addBatchNormalSoc } from "@/api/shebao/shebaoInfo.js";

export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    arr: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    value(v) {
      this.isCloseMethods = v;
      if (v) {
        this.staffList = this.arr;
      }
    }
  },
  data() {
    return {
      isCloseMethods: false,
      year: "",
      month: "",
      monthFormat: "YYYY-MM",
      typeValue: 1,
      defaultFangan: 0,
      progNameLists: [],
      defaultCard: 0,
      formData: [],
      isShebaoBase: false,
      payProvidentFund: false, // 是否缴纳公积金
      isGongJJBase: true,
      defaultGongjiJin: 0,
      onlySocAmount: false,
      Dvisible: false,
      staffList: []
    };
  },
  created() {
    this.checkShebaoMethod();

    this.init();
  },
  methods: {
    handleCancels() {
      this.isCloseMethods = false;
      this.$emit("input", false);
    },
    onYearMonthChange(date, dateString) {
      const s = dateString.split("-");
      this.year = s[0];
      this.month = s[1];
    },
    disabledDates(current) {
      // 只能选择当月往后的月份
      return current && current < moment().startOf("month"); // 月份第一天
    },
    // 业务类型选择
    onTypeChange(e) {
      this.typeValue = e.target.value;
    },
    // 批量正常参保
    onBatchNormalSoc() {
      // batchNormalSoc({
      //   companyId: this.$store.state.hr.companyId,
      //   empIdList: this.selectedRowKeys
      // })
      //   .then(res => {
      //     this.selectedRowKeys = [];
      //     this.getList();
      //     this.getEnum();
      //     this.getSelectEmpSocListCount();
      //     this.$message.success("批量正常参保成功!");
      //   })
      //   .catch(err => {
      //     this.$message.error("批量正常参保失败!");
      //     console.log("debug log --> ", err);
      //   });
    },

    // 创建参保选择方案
    chooseProgNames(value) {
      this.defaultFangan = value;
      this.progNameLists.map(item => {
        if (item.id === this.defaultFangan) {
          this.progId = this.defaultFangan;
          this.formData = this.deepCopy(item.socProgItemVOList);
          this.payProvidentFund = item.payProvidentFund;
          this.onlySocAmount = item.onlySocAmount;
          this.siteId = item.siteId;
          this.progKeyId = item.id;
        }
      });

      let d = -1;
      let d2 = -1;
      for (var i = 0; i < this.formData.length; i++) {
        const item = this.formData[i];
        if (item.itemType === 1) {
          // 社保
          if (this.onlySocAmount) {
            if (d === -1) {
              d = item.cardinalityDefaultAmount;
            }
            if (d !== item.cardinalityDefaultAmount) {
              // 展开
              this.isShebaoBase = false;
              return;
            }
          } else {
            if (d === -1) {
              d = item.cardinalityDefault;
            }
            if (d !== item.cardinalityDefault) {
              // 展开
              this.isShebaoBase = false;
              return;
            }
          }
        } else if (item.itemType === 2) {
          // 公积金
          if (this.onlySocAmount) {
            if (d2 === -1) {
              d2 = item.cardinalityDefaultAmount;
            }
            if (d2 !== item.cardinalityDefaultAmount) {
              // 展开
              this.isGongJJBase = false;
              return;
            }
          } else {
            if (d2 === -1) {
              d2 = item.cardinalityDefault;
            }
            if (d2 !== item.cardinalityDefault) {
              // 展开
              this.isGongJJBase = false;
              return;
            }
          }
        }
      }
    },
    // 设置社保基数
    setAllContent(val) {
      this.formData.map((item, index) => {
        if (item.itemType === 1) {
          if (this.onlySocAmount) {
            item.cardinalityDefaultAmount = this.defaultCard;
          } else item.cardinalityDefault = this.defaultCard;
        }
      });
    },
    // 编辑参保各项目基数
    editBaseInfo() {
      this.isShebaoBase = false;
    },
    returnEdit() {
      this.isShebaoBase = true;
    },
    finishEdit() {
      if ((this.defaultGongjiJin + "").trim() === "") {
        this.$message.success("公积金基数不能为空");
        return;
      }
      if ((this.defaultCard + "").trim() === "") {
        this.$message.success("个人社保基数不能为空");
        return;
      }
      console.log(this.defaultFangan);
      var that = this;
      if (!this.editPlan) {
        if (this.defaultFangan === 0) {
          that.$message.success("请先创建参保方案");
          return;
        } else {
          // 弹出添加增减员下一步对话框
          this.Dvisible = true;
        }
      }
      this.isCloseMethods = false;
      this.$emit("input", false);
    },
    returnEditGJ() {
      this.isGongJJBase = true;
    },
    setGongJiJinContent(val) {
      this.formData.map((item, index) => {
        if (item.itemType === 2) {
          if (this.onlySocAmount) {
            item.cardinalityDefaultAmount = this.defaultGongjiJin;
          } else item.cardinalityDefault = this.defaultGongjiJin;
        }
      });
    },
    editBaseInfoGJ() {
      this.isGongJJBase = false;
    },
    DhandleCancel() {
      this.isCloseMethods = true;
      this.$emit("input", true);
      this.Dvisible = false;
    },
    DhandleOk() {
      this.Dvisible = false;
      this.finishEdit2();
    },
    finishEdit2() {
      if (typeof this.month === "number" && this.month < 10) {
        this.month = "0" + this.month;
      }
      if (this.progId || this.progId === "") {
        const ids = [];
        this.staffList.map(item => {
          ids.push(item);
        });
        this.isCloseMethod = false;
        var d = ids.map(empId => ({
          onlySocAmount: this.onlySocAmount,
          payProvidentFund: this.payProvidentFund,
          companyId: this.$store.state.hr.companyId,
          // monthId: this.id,
          empId: empId,
          year: this.year,
          month: this.month,
          empSocItemDTOList: this.formData,
          empSocStatus: 1,
          progId: this.progId,
          businessType: this.typeValue,
          planFlag: true
        }));
        addBatchNormalSoc({ empSocInfoAddDTOList: d }).then(res => {
          this.progId = "";
          if (res.code === 200) {
            this.Lvisible = true;
            this.Dvisible = false;
            this.checkShebaoMethod();
            this.init();
            this.$emit("tap");
          }
        });
      }

      this.init(2);
    },
    init(type) {
      const nowDate = new Date();
      this.year = "" + nowDate.getFullYear();
      this.month = nowDate.getMonth() + 1;
      this.formData = [];
      this.defaultFangan = 0;
      this.isShebaoBase = true;
      this.isGongJJBase = true;
      if (type === 1) {
        this.dataDetail.map(item => {
          if (item.id === this.keyId) this.evprogName = item.progName;
        });
      }
      if (type === 2) {
        this.evprogName = "";
      }
    },
    // 深拷贝，解决引用赋值
    deepCopy(arr) {
      const newArr = [];
      arr.forEach((item, index) => {
        const record = {};
        for (const k in item) {
          record[k] = item[k];
        }
        newArr.push(record);
      });
      return newArr;
    },

    // 查询参保方案
    checkShebaoMethod() {
      getListAllRelation({ companyId: this.$store.state.hr.companyId }).then(res => {
        this.progNameLists = res.data;
        if (this.progNameLists.length !== 0) {
          this.defaultFangan = this.progNameLists[0].id;
          this.progNameLists.map(item => {
            if (item.id === this.defaultFangan) {
              this.progId = this.defaultFangan;
              this.formData = this.deepCopy(item.socProgItemVOList);
              this.payProvidentFund = item.payProvidentFund;
              this.onlySocAmount = item.onlySocAmount;
              this.siteId = item.siteId;
              this.progKeyId = item.id;
            }
          });
        }
      });
    },
    handleCancel() {
      this.init(2);
      this.isCloseMethods = false;
      this.Dvisible = false;
      this.$emit("input", false);
    },
    // 改变社保基数
    changeDefault(val, index) {
      if (this.onlySocAmount) {
        this.formData[index].cardinalityDefaultAmount = val;
      } else this.formData[index].cardinalityDefault = val;
    }
  }
};
</script>

<style lang="scss" scoped>
.rowdalog2 {
  display: flex;
  flex-direction: row;
  width: 100%;
}
.baseInfo-item {
  display: flex;
  flex-flow: row;
  // align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}
.baseInfo-item2 {
  width: 100%;
  display: flex;
  flex-flow: column;
  align-items: center;
  margin-bottom: 10px;
}
.shebao-base-box {
  width: 100%;
  background: #e8e8e8;
  margin: 24px 0;
  .base-header {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 12px;
    background: #e8e8e8;
    border-bottom: 1px solid #eee;
    span {
      margin-left: 5px;
    }
  }
  .baseInfo {
    padding: 24px 0 24px 56px;

    input,
    span {
      margin-left: 40px;
    }
  }
  .baseInfo-box {
    padding: 24px 0 12px 24px;
    input,
    span {
      margin-left: 10px;
    }
  }
}
</style>
